from django.contrib.auth import logout
from django.shortcuts import render

# Create your views here.
from django.views import View

from apps.users.models import User
from django.http import JsonResponse


class UsernameCountView(View):
    def get(self, request, username):
        count = User.objects.filter(username=username).count()
        return JsonResponse({'count': count})


class MobileCountView(View):
    def get(self, request, mobile):
        count = User.objects.filter(mobile=mobile).count()
        return JsonResponse({'count': count})


# 实现注册功能

import json
import re


class RegisterView(View):
    def post(self, request):
        # 1. 接收参数
        # 1.1 获取bytes数据
        body_bytes = request.body
        # 1.2 bytes转str
        body_str = body_bytes.decode()
        # 1.3 str转字典
        data = json.loads(body_str)
        # 2. 提取参数
        # 用户名，密码，确认密码，手机号和同意协议．　图片验证码和短信验证码　后期实现
        username = data.get('username')
        password = data.get('password')
        password2 = data.get('password2')
        mobile = data.get('mobile')
        allow = data.get('allow')
        # 3. 验证参数
        # 3.1 这五个参数都要有数据
        # all[变量名，变量名...]只要不是None或者False 就返回True 只要有一个为None, 或者False 就返回False
        if not all([username, password, password2, mobile, allow]):
            return JsonResponse({'code': 404, 'errmsg': '参数不全'})
        # 3.2 用户名需要符合规则　用户名也不能重复
        if not re.match('[0-9A-Za-z_]{5,20}', username):
            return JsonResponse({'code': 400, 'errmsg': '用户名不符合规则'})
        # 3.3　密码符合规则
        if not re.match('[0-9A-Za-z_]{8,20}', password):
            return JsonResponse({'code': 400, 'errmsg': '密码不符合规则'})
        # 3.4 密码和确认密码一直
        if password != password2:
            return JsonResponse({'code': 400, 'errmsg': '密码不一致'})
        # 3.5 手机号需要符合规则　手机号也不能重复
        if not re.match('1[3-9]\d{9}', mobile):
            return JsonResponse({'code': 400, 'errmsg': '手机号不符合规则'})
        # 3.6 同意协议

        # 4. 数据入库
        user = User.objects.create_user(
            username=username,
            password=password,
            mobile=mobile
        )
        # django 自带后台　－－　后台采用的session技术
        # diango 实现了　session 状态保持
        from django.contrib.auth import login
        # 参数１：request 请求对象
        # 参数２：user　用户信息
        # login(request,user)

        return JsonResponse({'code': 0, 'errmsg': 'ok'})


#####登录实现#############################################

class LoginView(View):
    def post(self, request):
        # 1. 接收参数
        data = json.loads(request.body.decode())
        # 2. 提取参数
        username = data.get('username')
        password = data.get('password')
        remembered = data.get('remembered')
        # 3. 验证参数
        if not re.match('[0-9a-zA-Z_]{5,20}', username):
            return JsonResponse({'code': 400, 'errmsg': '参数不全'})
        # 4. 判断用户名和密码是否正确
        # ①方式1
        # try:
        #     user = User.objects.get(username=username)
        # except User.DoesNotExist:
        #     return JsonResponse({'code':400,'errmsg':'用户名或密码不正确'})
        # else:
        #     if not user.check_password(password):
        #         return JsonResponse({'code':400,'errmsg':'用户名或密码不正确'})
        # 通过正则来判断 是手机号还是用户名
        if re.match('1[3-9]\d{9}', username):
            User.USERNAME_FIELD = 'mobile'
        else:
            User.USERNAME_FIELD = 'username'
        # ②方式2
        # authenticate 会自动的验证账号和密码
        # 如果账号和密码 正确 返回 user 对象
        # 如果账号和密码 错误 返回 None
        from django.contrib.auth import authenticate
        user = authenticate(username=username, password=password)
        if user is None:
            return JsonResponse({'code': 400, 'errmsg': '用户名或密码错误'})
        # 5. 状态保持 -- session
        from django.contrib.auth import login
        login(request, user)

        # 7. 返回响应
        response = JsonResponse({'code': 0, 'errmsg': 'ok'})

        # 6. 判断是否需要 n天免登陆
        # 首页用户名显示
        # cookie 实现
        if remembered:
            request.session.set_expiry(None)
            response.set_cookie('username', user.username, max_age=14 * 25 * 3600)
        else:
            request.session.set_expiry(0)
            response.set_cookie('username', user.username)
        return response


########退出登录######################################################
class LogoutView(View):
    def delete(self, request):
        # 方式一
        # request.session.clear()
        # request.session.flush()
        # 方式二
        # 1. 删除状态保持信息
        from django.contrib.auth import logout
        logout(request)
        # 2. 把username 的cookie信息删除
        response = JsonResponse({'code': 0, 'errmsg': 'ok'})
        response.delete_cookie('username')
        return response


##########个人中心展示##############################################

from django.contrib.auth.mixins import LoginRequiredMixin
from utils.user import LoginRequiredJSONMixin

class UserCenterView(LoginRequiredJSONMixin, View):
    def get(self, request):
        # 1. 获取登录用户信息
        user = request.user
        # 2. 组织为JSON数据
        info_data = {
            'username': user.username,
            'mobile': user.mobile,
            'email': user.email,
            'email_active': user.email_active
        }
        # 返回响应
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'info_data': info_data})


from utils.user import LoginRequiredJSONMixin

class EmailView(View):
    def put(self,request):
        # 1. 获取请求参数
        data = json.loads(request.body.decode())
        # 2. 提取参数
        email = data.get('email')
        # 3. 验证参数
        if not re.match('^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$',email):
            return JsonResponse({'code':400,'errmsg':'邮箱格式不正确'})
        # 4. 更新数据
        request.user.email = email
        request.user.save()

        from django.core.mail import send_mail
        # # 主题
        # subject = '美多商城激活邮件'
        # # 消息 内容
        # message = ''
        # #　发件人
        # from_email = '美多商城官方邮箱<13111113136@163.com>'
        # # 收件人列表
        # recipient_list = [email]
        # html_message = '<a href="#">点击激活</a>'
        # send_mail(subject,
        #           message,
        #           from_email,
        #           recipient_list,
        #           html_message=html_message)
        from apps.users.common import generic_email_token

        token = generic_email_token(email,request.user.id)
        # url 的前边是固定的
        verify_url = 'http://www.meiduo.site:8080/success_verify_email.html?token=%s'%token
        # 调用异步发送邮件的任务
        from celery_meiduo.email.tasks import celery_send_email
        celery_send_email.delay(email,verify_url)
        # 5. 返回响应
        return JsonResponse({'code':0})


class EmailVerificationView(View):
    def put(self,request):
        # 1. 接收参数 token
        # 2. 提取参数 token
        token = request.GET.get('token')
        # 3. 验证参数
        if token is None:
            return JsonResponse({'code':400, 'errmsg':'没有token信息'})
        # 4. 对token进行解密操作
        from apps.users.common import check_email_token
        data = check_email_token(token)
        if data is None:
            return JsonResponse({'code':400, 'errmsg':'token过期或者损坏'})
        # 5. 根据解密的数据查询用户信息
        email = data.get('email')
        user_id = data.get('user_id')
        try:
            user = User.objects.get(email=email,id=user_id)
        except User.DoesNotExist:
            return JsonResponse({'code':400,'errmsg':'没有该用户'})
        # 6. 改变邮箱激活状态
        user.email_active = True
        user.save()
        # 7. 返回响应
        return JsonResponse({'code':0,'errmsg':'ok'})



from apps.users.models import Address
from utils.user import LoginRequiredJSONMixin

class CreateAddressView(LoginRequiredJSONMixin,View):
    def post(self,request):
        # 1. 接收参数
        json_dict = json.loads(request.body.decode())
        # 2. 提取参数
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')
        # 3. 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return http.HttpResponseBadRequest('缺少必传参数')
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseBadRequest('参数mobile有误')
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.HttpResponseBadRequest('参数tel有误')
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.HttpResponseBadRequest('参数email有误')
        # 4. 数据入库
        try:
            address = Address.objects.create(
                user=request.user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )
            # 设置默认地址
            if not request.user.default_address:
                request.user.default_address = address
                request.user.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code':400,'errmsg':'新增地址失败'})

        # 5. 返回响应
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }
        return JsonResponse({'code':0,'errmsg':'新增地址成功', 'address':address_dict})


class AddressListView(LoginRequiredJSONMixin,View):
    def get(self,request):
        # 1. 根据需求查询数据
        addresses=Address.objects.filter(user=request.user,is_deleted=False)
        # 2. 将对象转换为字典数据
        addresses_list = []
        for address in addresses:
            addresses_list.append({
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email
            })
        # 返回响应
        return JsonResponse({
            'code':0,
            'errmsg':'ok',
            'addresses':addresses_list,
            'default_address_id':request.user.default_address_id
        })


class UpdateDestroyAddressView(LoginRequiredJSONMixin,View):
    '''修改地址'''
    def put(self,request,address_id):
        # 1. 接收参数
        json_dict = json.loads(request.body.decode())
        # 2. 提取参数
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')
        # 3. 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return http.JsonResponse({'code': 400,
                                      'errmsg': '缺少必传参数'})

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'code': 400,
                                      'errmsg': '参数mobile有误'})

        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.JsonResponse({'code': 400,
                                          'errmsg': '参数tel有误'})
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.JsonResponse({'code': 400,
                                          'errmsg': '参数email有误'})
        # 4. 判断地址是否存在
        try:
            Address.objects.filter(id=address_id).update(
                user=request.user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '更新地址失败'})

        # 构造响应数据
        address = Address.objects.get(id=address_id)
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }
        # 响应更新地址结果
        return JsonResponse({'code': 0, 'errmsg': '更新地址成功', 'address': address_dict})

    '''删除地址'''
    def delete(self, request, address_id):
        """删除地址"""
        try:
            # 查询要删除的地址
            address = Address.objects.get(id=address_id)

            # 将地址逻辑删除设置为True
            address.is_deleted = True
            address.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '删除地址失败'})

        # 响应删除地址结果
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        # 响应保存结果
        return JsonResponse({'code': 0, 'errmsg': '删除地址成功', 'address': address_dict})


class DefaultAddressView(LoginRequiredJSONMixin,View):
    def put(self,request,address_id):
        try:
            # 接收参数,查询地址
            address = Address.objects.get(id=address_id)
            # 设置地址为默认地址
            request.user.default_address = address
            request.user.save()
        except Exception as e:
            logger.error(e)

            return http.JsonResponse({'code':400,'errmsg':'设置默认地址失败'})

        # 返回响应
        return JsonResponse({'code':0,'errmsg':'设置默认地址成功'})

class UpdateTitleAddressView(LoginRequiredJSONMixin,View):
    def put(self,request,address_id):
        # 接收参数
        json_dict = json.loads(request.body.decode())
        title = json_dict.get('title')

        try:
            # 查询地址
            address = Address.objects.get(id=address_id)
            # 设置新的标题
            address.title = title
            address.save()
        except Exception as a:
            logger.error(e)
            return http.JsonResponse({'code': 400,'errmsg':'设置标题失败'})

        # 返回响应
        return JsonResponse({'code':0,'errmsg':'设置标题成功'})


from apps.goods.models import SKU
from django_redis import get_redis_connection

class UserHistoryView(LoginRequiredJSONMixin,View):
    def post(self,request):
        user = request.user

        # 1. 接受请求
        data = json.loads(request.body.decode())
        # 2. 提取参数
        sku_id = data.get('sku_id')
        # 3. 验证参数
        try:
            sku = SKU.objects.get(id = sku_id)
        except SKU.DoesNotExist:
            return JsonResponse({'code':400,'errmsg':'没有此商品'})
        # 4. 数据入库
        redis_cli = get_redis_connection('history')
        # 4.1 先去重
        redis_cli.lrem(user.id,0,sku_id)
        # 4.2 再添加
        redis_cli.lpush(user.id,sku_id)
        # 4.3 保证列表中有5条浏览记录
        redis_cli.ltrim(user.id,0,4)

        # 5. 返回响应
        return JsonResponse({'code':0})

    def get(self,request):
        # 1. 必须是登录用户 LoginRequiredJSONMixin
        # 2. 获取用户信息
        user = request.user
        # 3. 连接redis
        redis_cli = get_redis_connection('history')
        # 4. 查询浏览记录
        sku_ids = redis_cli.lrange(user.id,0,-1)
        skus = []
        # 5. 遍历列表数据 查询商品详细信息
        for id in sku_ids:
            sku = SKU.objects.get(id=id)
            # 6. 将对象转换为字典数据
            skus.append({
                'id':sku.id,
                'name':sku.name,
                'price':sku.price,
                'default_image_url':sku.default_image.url   # url 调用自定义存储类url属性
            })
        # 返回响应
        return JsonResponse({'code':0,'skus':skus,'errmsg':'ok'})


class ChangePasswordView(LoginRequiredJSONMixin, View):
    def put(self,request):
        # 1. 接收参数
        dict = json.loads(request.body.decode())
        # 2. 提取参数
        old_password = dict.get('old_password')
        new_password = dict.get('new_password')
        new_password2 = dict.get('new_password2')
        # 3. 校验参数
        if not all([old_password,new_password,new_password2]):
            return JsonResponse({'code':400,'errmsg':'缺少必传参数'})

        result = request.user.check_password(old_password)
        if not result:
            return JsonResponse({'code':400,'errmsg':'原始密码不正确'})

        if not re.match(r'^[0-9A-Za-z]{8,20}$',new_password):
            return JsonResponse({'code':400,'errmsg':'密码最少8为,最长20位'})

        if new_password != new_password2:
            return JsonResponse({'code':400,'errmsg':'两次输入密码不一致'})

        # 4. 修改密码
        try:
            request.user.set_password(new_password)
            request.user.save()
        except Exception:
            return JsonResponse({'code':0,'errmsg':'修改密码失败'})

        # 5. 清理状态保持信息
        logout(request)

        response = JsonResponse({'code':0,'errmsg':'ok'})
        response.delete_cookie('username')

        # 6. 返回响应修改密码结果 重定向到登录界面
        return response